package com.hong.utils.executors;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @Auther: Administrator
 * @Date: 2018/7/28 19:14
 * @Description:
 */
public class FutureExample2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
//        testIsDone();
//        testCancel();
        testCancel2();
    }


    private static void testIsDone() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        Future<Integer> future = executorService.submit(()->{
            /*try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return 10;*/
            throw  new RuntimeException();
        });
        try {
            Integer result = future.get();
            System.out.println(result );
        }catch (Exception e){
            System.out.println(" is done "  +future.isDone());
        }

    }

    /**
     * try to cancel maybe failed
     * <ul>
     *     <li>task is completed already.</li>
     *     <li>has already been cancelled.</li>
     * </ul>
     *
     */
    private static void testCancel() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        AtomicBoolean running = new AtomicBoolean(true);
        Future<Integer> future = executorService.submit(()->{
            /*try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            while (running.get()){

            }
            return 10;
        });
        TimeUnit.MILLISECONDS.sleep(10);
        System.out.println(future.cancel(true));
        System.out.println(future.isDone());
        System.out.println(future.isCancelled());

    }

    private static void testCancel2() throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        Future<Integer> future = executorService.submit(()->{
            /*try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            while (!Thread.interrupted()){ }
            System.out.println("111111111111111");
            return 10;
        });
        TimeUnit.MILLISECONDS.sleep(10);
        System.out.println(future.cancel(true));
        System.out.println(future.isDone());
        System.out.println(future.isCancelled());

    }

}
